package com.polaris.live.popup

import android.content.Context
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import androidx.core.content.ContextCompat
import com.blankj.utilcode.util.SpanUtils
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.CenterPopupView
import com.polaris.live.R
import com.polaris.live.common.cacha.CacheUtil
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.manager.CoroutineScopeManager
import com.polaris.live.databinding.PopupPriceModificationPromptBinding
import com.polaris.live.utils.image.ImageUtils
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 *  修改价格提示
 * @author Created by 天晴 on 2024/2/27 19:18
 * @since 1.0.0
 **/
class PriceModificationPromptPopup(
    context: Context,
    private val message: String,
    private val onOk: () -> Unit,
) : CenterPopupView(context) {

    private lateinit var mBinding: PopupPriceModificationPromptBinding
    override fun getImplLayoutId(): Int {
        return R.layout.popup_price_modification_prompt
    }

    private var job: Job? = null

    override fun onCreate() {
        super.onCreate()
        mBinding = PopupPriceModificationPromptBinding.bind(popupImplView)

        job = CoroutineScopeManager.ioScope.launch {
            try {
                val span = createSpan()

                withContext(CoroutineScopeManager.mainDispatcher) {
                    mBinding.message.text = span.create()
                }
            } finally {
                if (coroutineContext[Job] == job) {
                    job = null
                }
            }
        }

        mBinding.ok.setOnSingleClickListener {
            dismiss()
            onOk.invoke()
        }
    }

    private suspend fun createSpan(): SpanUtils {
        val span = SpanUtils.with(mBinding.message)
        val splitMessage = message.split(SPLIT)

        val list = splitMessage
            .filter {
                it.contains(TEXT) && it.replace(TEXT, "").isNotEmpty()
            }
            .map { "" }

        splitMessage.forEach { msg ->
            if (msg.contains(IMAGEAND)) {
                val modifiedStr = msg.replace(IMAGEAND, "")

                val icon = when {
                    modifiedStr.endsWith("/free.png") -> {
                        ImageUtils.loadImage(context, R.drawable.party_game_free, 40f, 19.2f)
                    }
                    modifiedStr.endsWith("/coin.png") -> {
                        ImageUtils.loadImage(context, R.drawable.party_game_mod_zs2, 14f, 14f)
                    }
                    modifiedStr.endsWith("/game-coin.png") -> {
                        ImageUtils.loadImage(context, R.drawable.party_game_mod_yxb2, 14f, 14f)
                    }
                    else -> {
                        if (list.isEmpty()) {
                            ImageUtils.loadNetImageBitmapNoTransform(context, modifiedStr, 40f, 14f)
                        } else {
                            ImageUtils.loadNetImageBitmap(context, modifiedStr, 14, 14)
                        }
                    }
                }

                if (icon is Drawable) {
                    span.appendImage(icon, SpanUtils.ALIGN_CENTER)
                } else if (icon is Bitmap && !icon.isRecycled) {
                    span.appendImage(icon, SpanUtils.ALIGN_CENTER)
                }
            } else if (msg.contains(TEXT)) {
                val modifiedStr = msg.replace(TEXT, "")
                span.append(modifiedStr)
                    .setForegroundColor(
                        ContextCompat.getColor(
                            context,
                            com.polaris.live.common.R.color.color_fe1849
                        )
                    )
            } else {
                span.append(msg)
            }
        }
        return span
    }

    override fun dismiss() {
        job?.cancel()
        job = null

        super.dismiss()
    }

    companion object {

        const val SPLIT = "<#>"
        const val IMAGEAND = "image="
        const val TEXT = "text="
        fun show(
            context: Context,
            message: String,
            onOk: () -> Unit,
        ) {
            //存弹窗时间
            CacheUtil.setLastGameWinPopTime(CacheUtil.getServerTime())
            XPopup.Builder(context)
                .hasNavigationBar(false)
                .isDestroyOnDismiss(true)
                .asCustom(PriceModificationPromptPopup(context, message, onOk))
                .show()
        }
    }
}